package com.shj.web.controller;

import com.shj.service.SysUserRoleService;
import com.shj.web.security.entity.SelfUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (SysUserRole)表控制层
 *
 * @author makejava
 * @since 2020-03-12 13:00:29
 */
@Slf4j
@Controller
public class SysUserRoleController {
    /**
     * 服务对象
     */
    @Resource
    private SysUserRoleService sysUserRoleService;

    /**
     * @Description 用户登录后调用的接口，直接从安全上下文中获取用户角色
     * @author songhuajian
     * @date 2020/4/2 20:05
     */
    @GetMapping("/sysUserRoles")
    @ResponseBody
    public Map<String, Object> getUserRole(ServletRequest request, ServletResponse response){
        // 从security上下文中获取用户信息
        SelfUserEntity selfUserEntity = (SelfUserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 获取角色和用户Id
        Map<String, Object> data = new HashMap<>(16);
        List<String> list = new ArrayList<>();
        for (GrantedAuthority authority : selfUserEntity.getAuthorities()){
            list.add(authority.getAuthority());
        }
        data.put("roles", list);
        data.put("name", selfUserEntity.getUserId());
        // 返回数据
        return data;
    }

}